<template>
  <div >
    <a-card :bordered="false" v-if="!id" style="margin-bottom:24px;">
        <a-form-model ref="form" :model="formData" layout="inline" >
          <a-form-model-item label="锁定数据">
              <a-tooltip
                    placement="top"
                    title="点击开启后对新增规则里面选择角色，通过角色选择用户进行锁定数据"
                    style="margin-right:10px;"
                >
                <a-icon type="question-circle" />
              </a-tooltip>
              <a-radio-group v-model="formData.status">
                <a-radio :value="'1'">开启</a-radio>
                <a-radio :value="'0'">关闭</a-radio>
              </a-radio-group>
              
            </a-form-model-item>
            <a-space style="margin-top:5px;margin-left:100px;">
                <a-button type="primary" :loading="loadingConfig" @click="onSave" :disabled="!hasBeenSavedRule">保存配置</a-button>
            </a-space>
        </a-form-model> 
    </a-card>

    <a-row :gutter="10" >
      <a-col :md="leftColMd" :sm="24" style="margin-bottom: 20px;">
        <a-card :bordered="false">
          <div style="text-align: right;height:24px;" >
            <a-icon type="rollback" @click="onCancel" v-if="this.rightcolval == 0"/>
          </div>
          <!-- 查询区域 -->
          <div class="table-page-search-wrapper" v-if="!id">
            <!-- 搜索区域 -->
            <a-form layout="inline" @keyup.enter.native="searchQuery">
              <a-row :gutter="24">
                <a-col :md="8" :sm="8">
                  <a-form-item label="规则名称">
                    <a-input placeholder="" v-model="queryParam.ruleName"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="8">
                  <a-form-item label="角色名称">
                    <a-input placeholder="" v-model="queryParam.roleName"></a-input>
                  </a-form-item>
                </a-col>
                <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                  <a-col :md="8" :sm="8">
                    <a-button type="primary" @click="searchQuery" icon="search" style="margin-left: 21px">查询</a-button>
                    <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
                  </a-col>
                </span>
              </a-row>
            </a-form>
          </div>
          <!-- 操作按钮区域 -->
          <div class="table-operator" style="margin: 5px 0 10px 2px" v-if="!id">
            <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
          </div>
          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
            <i class="anticon anticon-info-circle ant-alert-icon">
            </i> 已选择 <a><b>{{ selectedRowKeys1.length }}</b></a>项
            <a style="margin-left: 24px" @click="onClearSelected1">清空</a>
          </div>
          <div style="margin-top: 15px">
            <a-table
              style="height:500px"
              ref="table"
              size="default"
              rowKey="id"
              :columns="columns"
              :dataSource="dataSource"
              :pagination="ipagination"
              :loading="loading"
              :rowSelection="{selectedRowKeys: selectedRowKeys1, onChange: onSelectChange1, type:'radio'}"
              @change="handleTableChange">
              <span slot="action" slot-scope="text, record">
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete1(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </span>
            </a-table>
          </div>
          <!-- 表单区域 -->
          <rule-modal ref="modalForm" @ok="modalFormOk"></rule-modal>
        </a-card>
      </a-col>
      <a-col :md="rightColMd" :sm="24" v-if="this.rightcolval == 1">
        <a-card :bordered="false">
          <div style="text-align: right;height:24px;">
            <a-icon type="rollback" @click="onCancel" style="margin-right:20px;"/>
            <a-icon type="close-circle" @click="hideUserList" />
          </div>
          <!-- 查询区域 -->
          <div class="table-page-search-wrapper">
            <a-form layout="inline">
              <a-row :gutter="24">

                <a-col :md="12" :sm="12">
                  <a-form-item label="用户账号">
                    <a-input placeholder="" v-model="queryParam2.username"></a-input>
                  </a-form-item>
                </a-col>
                <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                  <a-col :md="9" :sm="24">
                  <a-button type="primary" @click="searchQuery2" icon="search" style="margin-left: 21px">查询</a-button>
                    <a-button type="primary" @click="searchReset2" icon="reload" style="margin-left: 8px">重置</a-button>

                  </a-col>
                </span>
              </a-row>
            </a-form>
          </div>
          <!-- 操作按钮区域 -->
          <div class="table-operator" style="margin: 5px 0 10px 2px">
            <a-button @click="onSaveRole" :loading="loadingSaveRole" type="primary" :disabled="selectedRowKeys2.length == 0">保存</a-button>
          </div>

          <!-- table区域-begin -->
          <div>
            <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
              <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
              selectedRowKeys2.length }}</a>项
              <a style="margin-left: 24px" @click="onClearSelected2">清空</a>
            </div>
            <a-table
              style="height:500px"
              ref="table2"
              size="default"
              rowKey="id"
              :columns="columns2"
              :dataSource="dataSource2"
              :pagination="ipagination2"
              :loading="loading2"
              :rowSelection="{selectedRowKeys: selectedRowKeys2, onChange: onSelectChange2}"
              @change="handleTableChange2">
            </a-table>
          </div>
       </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { filterObj } from '@/utils/util'
import {publicApi,ruleList,ruleEdit,userRoleList,lockUserAdd,lockUserList} from '@/api/warning/Policy.js'
import RuleModal from './RuleModal.vue'
  export default {
    mixins: [JeecgListMixin],
    components: {RuleModal },
    inject:['closeCurrent'],
    data () {
      return {
        formData:{status:'0'},
        model1: {},
        model2: {},
        currentRoleId: '',
        queryParam2: {},
        dataSource2: [],
        ipagination2: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        isorter2: {
          column: 'createTime',
          order: 'desc'
        },
        filters2: {},
        loading2: false,
        selectedRowKeys1: [],
        selectedRowKeys2: [],
        selectionRows1: [],
        selectionRows2: [],
        rightcolval:0,
        columns:
          [
            {
              title: '序号',
              dataIndex: '',
              key: 'rowIndex',
              width: 80,
              // align: 'center',
              customRender: (text, record, index) =>
                `${(this.ipagination.current - 1) * this.ipagination.pageSize +
                  (index + 1)}` //序号分页后连续
            },
            {
              title: '规则名称',
              align: 'center',
              dataIndex: 'ruleName'
            },
            {
              title: '角色名称',
              align: 'center',
              dataIndex: 'roleName'
            },
            {
              title: '角色编码',
              dataIndex: 'roleCode',
              align:"center",
            },
            {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            scopedSlots: { customRender: 'action' }
          }
          ],
          columns2: [
            {
            title: '用户账号',
            align: 'center',
            dataIndex: 'username',
            width: 120
            },
            {
              title: '用户名称',
              align: 'center',
              width: 100,
              dataIndex: 'realname'
            },
            {
              title: '状态',
              align: 'center',
              width: 80,
              dataIndex: 'status_dictText'
            },
          ],
        // 高级查询参数
        superQueryParams2: '',
        // 高级查询拼接条件
        superQueryMatchType2: 'and',
 
        hasBeenSavedRule:false,
        id:this.$route.query.id,
        loadingSaveRole:false,
        loadingConfig:false,
        url: {
          delete: publicApi.ruleDelete,
        }
      }
    },
    computed: {
      leftColMd() {
        return this.selectedRowKeys1.length === 0 ? 24 : 12
      },
      rightColMd() {
        return this.selectedRowKeys1.length === 0 ? 0 : 12
      }
    },
    methods: {
      onCancel(){
        this.closeCurrent()
        this.$router.push({path:'/earlyWarning/strategy/lockRule/list'});
      },
      onSave(){
        this.$refs.form.validate(valid => {
          if (valid) {
            this.loadingConfig = true;
            console.log("form",this.formData);
            let params = {
              id:this.selectionRows1[0].id,
              status:this.formData.status
            }
            ruleEdit(params).then((res) => {
              if (res.success) {
                this.$message.success("保存配置成功");
              }else{
                this.$message.warning(res.message?res.message:'请求失败！')
              }
            }).catch(e=>{
              this.$message.warning("请求失败！");
            }).finally(() => {
              this.loadingConfig = false;
            })
          }
        })
      },
      onSaveRole(){
        console.log("selectedRowKeys2",this.selectedRowKeys2);
        this.loadingSaveRole = true;
        let params = {
          id:this.selectionRows1[0].id,
          userIds:this.selectedRowKeys2.join(',')
        }
        lockUserAdd(params).then((res) => {
          if (res.success) {
              this.hasBeenSavedRule = true
              this.$message.success("保存成功")
          } else {
              this.$message.warning(res.message?res.message:'请求失败！')
          }
        }).catch(e=>{
              this.$message.warning("请求失败！");
        }).finally(() => {
               this.loadingSaveRole = false;
        })

      },
      onClearSelected1() {
        this.rightcolval = 0
        this.selectedRowKeys1 = []
        this.selectionRows1 = []
      },
      onClearSelected2() {
        this.selectedRowKeys2 = []
        this.selectionRows2 = []
      },
      onSelectChange1(selectedRowKeys, selectionRows) {
        this.rightcolval = 1
        this.selectedRowKeys1 = selectedRowKeys
        this.selectionRows1 = selectionRows
        this.model1 = Object.assign({}, selectionRows[0])
        console.log(this.model1)
        this.onClearSelected2()
        this.hasBeenSavedRule = false
        this.currentRoleId = selectionRows[0].roleId
        this.formData.status = selectionRows[0].status?selectionRows[0].status:'0'
        this.loadData2()
      },
      onSelectChange2(selectedRowKeys, selectionRows) {
        this.selectedRowKeys2 = selectedRowKeys
        this.selectionRows2 = selectionRows
          console.log("this.selectedRowKeys2",this.selectedRowKeys2);
      },
      handleTableChange2(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        //TODO 筛选
        if (Object.keys(sorter).length > 0) {
          this.isorter2.column = sorter.field
          this.isorter2.order = 'ascend' == sorter.order ? 'asc' : 'desc'
        }
        this.ipagination2 = pagination
        this.loadData2()
      },
      hideUserList(){
        this.rightcolval = 0
        this.selectedRowKeys1 = []
      },
      getQueryParams2() {
        //获取查询条件
        let sqp = {}
        if (this.superQueryParams2) {
          sqp['superQueryParams'] = encodeURI(this.superQueryParams2)
          sqp['superQueryMatchType'] = this.superQueryMatchType2
        }
        var param = Object.assign(sqp, this.queryParam2, this.isorter2, this.filters2)
        param.field = this.getQueryField2()
        param.pageNo = this.ipagination2.current
        param.pageSize = this.ipagination2.pageSize
        return filterObj(param)
      },
      getQueryField2() {
        //TODO 字段权限控制
        var str = 'id,'
        this.columns2.forEach(function(value) {
          str += ',' + value.dataIndex
        })
        return str
      },
      loadData(arg) {
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        var params = this.getQueryParams();//查询条件
        if(this.id){
          params.id = this.id;
        }
        this.loading = true;
        ruleList(params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records||res.result;
            this.ipagination.total = res.result.total;
          }else{
            this.$message.warning(res.message?res.message:'请求失败！')
          }
        }).catch(e=>{
          this.$message.warning("请求失败！");
        }).finally(() => {
          this.loading = false
        })
      },
      loadData2(arg) {
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination2.current = 1
        }
        if (this.currentRoleId === '') return
        let params = this.getQueryParams2()//查询条件
        params.roleId = this.currentRoleId
        this.loading2 = true
        userRoleList(params).then((res) => {
          if (res.success) {
            this.dataSource2 = res.result.records
            this.ipagination2.total = res.result.total
            if(this.id){
              this.lockuserList()
            }
          }else{
            this.$message.warning(res.message?res.message:'请求失败！')
            
          }
        }).catch(e=>{
          this.$message.warning("请求失败！");
        }).finally(() => {
          this.loading2 = false
        })

      },
      lockuserList() {
        let params = {
          lockRuleId:this.id
        }
        lockUserList(params).then((res) => {
         if (res.success) {
           this.selectionRows2 = res.result
           this.selectedRowKeys2 =  this.selectionRows2.map(val=>{return val.userId})
          }else{
            this.$message.warning(res.message?res.message:'请求失败！')
          }
        }).catch(e=>{
          this.$message.warning("请求失败！");
        }).finally(() => {
           this.loading2 = false
        })
      },
      searchQuery2() {
        this.loadData2(1)
      },
      searchReset2() {
        this.queryParam2 = {}
        this.loadData2(1)
      },
      handleDelete1(id) {
        this.handleDelete(id)
        this.dataSource2 = []
        this.currentRoleId = ''
      },
    }
  }
</script>

<style lang="less" scoped>
 
</style>